﻿#region Copyright Notice
// This file is part of GestionPedago.
// <description>
// Copyright (C) 2012 ENI Ecole Informatique
// 
// GestionPedago is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// <program> is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.IO;
using System.Diagnostics;
using GestionPedago.Services.ES.Modele;
using GestionPedago.Services;
using GestionPedago.Services.ES;
using System.Windows;
using GestionPedago.View;
using System.ComponentModel;
using System.Windows.Data;

namespace GestionPedago.ViewModel {
    
    /// <summary>
    /// Classe qui représente l'onglet d'Edition d'ECF
    /// </summary>
    public class CreationModificationECFVM : OngletVM
    {

        /// <summary>
        /// ECF Courrant
        /// </summary>
        private ECFES CurrentECF { get; set; }

        private ICommand newECFCommand;
        private ICommand saveECFCommand;
        private ICommand deleteECFCommand;

        private ICommand addModuleCommand;
        private ICommand delModuleCommand;

        private ICommand addCompetenceCommand;
        private ICommand delCompetenceCommand;


        private string _libelle;
        /// <summary>
        /// Libellé de l'ECF
        /// </summary>
        public string Libelle
        {
            get { return _libelle; }
            set
            {
                _libelle = value;
                RaisePropertyChanged("Libelle");
            }
        }

        /// <summary>
        /// Liste des versions de l'ECF
        /// </summary>
        public ObservableCollection<VersionECFES> Versions { get; set; }

        private ObservableCollection<ModuleES> _modulesRestants;
        /// <summary>
        /// Liste des modules non liés à l'ECF
        /// </summary>
        public ObservableCollection<ModuleES> ModulesRestants 
        { 
            get { return _modulesRestants; }
            set
            {
                _modulesRestants = value;
                RaisePropertyChanged("ModulesRestants");
            }
        }

        private ObservableCollection<ModuleES> _modulesUtilises;
        /// <summary>
        /// Liste des modules lié à l'ECF
        /// </summary>
        public ObservableCollection<ModuleES> ModulesUtilises
        {
            get { return _modulesUtilises; }
            set
            {
                _modulesUtilises = value;
                RaisePropertyChanged("ModulesUtilises");
            }
        }

        private ObservableCollection<CompetenceES> _competencesRestantes;
        /// <summary>
        /// Liste des compétences non liées à l'ECF
        /// </summary>
        public ObservableCollection<CompetenceES> CompetencesRestantes
        {
            get { return _competencesRestantes; }
            set
            {
                _competencesRestantes = value;
                RaisePropertyChanged("CompetencesRestantes");
            }
        }

        private ObservableCollection<CompetenceES> _competencesUtilisees;
        /// <summary>
        /// Liste des compétences liées à l'ECF
        /// </summary>
        public ObservableCollection<CompetenceES> CompetencesUtilisees
        {
            get { return _competencesUtilisees; }
            set
            {
                _competencesUtilisees = value;
                RaisePropertyChanged("CompetencesUtilisees");
            }
        }


        /// <summary>
        /// Liste des documents liés à l'ECF
        /// </summary>
        public ObservableCollection<FileInfo> Documents { get; set; }


        

        /// <summary>
        /// Constructeur de la classe CreationModificationECFVM
        /// </summary>
        /// <param name="parent">Gestionnaire d'onglets</param>
        /// <param name="ecf">ECF à éditer. (Optionnel)</param>
        public CreationModificationECFVM(GestionnaireOngletsVM parent, ECFES ecf = null) 
        {
            base.Parent = parent;
            base.DisplayName = @"Créer / Modifier un ECF";

            if (ecf == null)
            {
                              
                ModulesRestants = new ObservableCollection<ModuleES>(FacadeServices.GetInstance().RecupererModules(new RecupererModulesIn()).ListeModules);
                ModulesUtilises = new ObservableCollection<ModuleES>();

                CompetencesRestantes = new ObservableCollection<CompetenceES>(FacadeServices.GetInstance().RecupererCompetences(new RecupererCompetencesIn()).ListeCompetences);
                CompetencesUtilisees = new ObservableCollection<CompetenceES>();

                Versions = new ObservableCollection<VersionECFES>();
                Documents = new ObservableCollection<FileInfo>();
            }
            else
            {
                CurrentECF = ecf;

                Libelle = ecf.Libelle;

                ModulesUtilises = (ecf.ListeModule != null) ? new ObservableCollection<ModuleES>(ecf.ListeModule) : new ObservableCollection<ModuleES>();
                ModulesRestants = new ObservableCollection<ModuleES>(FacadeServices.GetInstance().RecupererModules(new RecupererModulesIn()).ListeModules);
                foreach (ModuleES m in ModulesUtilises)
                    ModulesRestants.Remove(m);

                CompetencesUtilisees = (ecf.ListeCompetence != null) ? new ObservableCollection<CompetenceES>(ecf.ListeCompetence) : new ObservableCollection<CompetenceES>();
                CompetencesRestantes = new ObservableCollection<CompetenceES>(FacadeServices.GetInstance().RecupererCompetences(new RecupererCompetencesIn()).ListeCompetences);
                foreach (CompetenceES c in CompetencesUtilisees)
                    CompetencesRestantes.Remove(c);

                Versions = (ecf.ListeVersionECF != null) ? new ObservableCollection<VersionECFES>(ecf.ListeVersionECF) : new ObservableCollection<VersionECFES>() ;
                Documents = new ObservableCollection<FileInfo>();
            }

        }


        public ICommand SaveECFCommand
        {
            get
            {
                if (this.saveECFCommand == null)
                    this.saveECFCommand = new RelayCommand(param => this.EnregistrerECF());

                return this.saveECFCommand;
            }
        }

        /// <summary>
        /// Enregistrer l'ECF courrant
        /// </summary>
        public void EnregistrerECF()
        {
            if (!string.IsNullOrWhiteSpace(Libelle))
            {
                if(MessageBox.Show("Enregistrer cet ECF ?", "Enregistrer", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
                
                    try
                    {
                        Parent.vmMainWindow.vmBarreInfos.Message = "Enregistrement en cours ...";

                        if (CurrentECF == null)
                            CurrentECF = new ECFES();

                        CurrentECF.Libelle = Libelle;
                        CurrentECF.ListeVersionECF = Versions.ToList();
                        CurrentECF.ListeModule = ModulesUtilises.ToList();
                        CurrentECF.ListeCompetence = CompetencesUtilisees.ToList();

                        EnregistrerECFOut paramSortie = FacadeServices.GetInstance().EnregistrerECF(new EnregistrerECFIn(CurrentECF));
                        CurrentECF = paramSortie.ECF;

                        Parent.RefreshAfterEditECF();

                        Parent.vmMainWindow.vmBarreInfos.Message = "Enregistrement correctement effectué.";

                        Parent.Onglets.Remove(this);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Erreur lors de l'enregistrement :\n" + e.Message, "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("Vous devez saisir un libellé.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }


        public ICommand NewECFCommand
        {
            get
            {
                if (this.newECFCommand == null)
                    this.newECFCommand = new RelayCommand(param => this.ResetOnglet());

                return this.newECFCommand;
            }
        }

        /// <summary>
        /// Réinitialise tous les champs pour un nouvel ECF
        /// </summary>
        public void ResetOnglet()
        {
            if (MessageBox.Show("Créer un nouvel ECF ?", "Nouveau", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                try
                {
                    CurrentECF = new ECFES();
                    Libelle = "";
                    ModulesRestants.Clear();
                    ModulesUtilises.Clear();
                    CompetencesUtilisees.Clear();
                    CompetencesRestantes.Clear();

                    ModulesRestants = new ObservableCollection<ModuleES>(FacadeServices.GetInstance().RecupererModules(new RecupererModulesIn()).ListeModules);
                   
                    ModulesUtilises = new ObservableCollection<ModuleES>();
                    
                    CompetencesRestantes = new ObservableCollection<CompetenceES>(FacadeServices.GetInstance().RecupererCompetences(new RecupererCompetencesIn()).ListeCompetences);
                    
                    CompetencesUtilisees = new ObservableCollection<CompetenceES>();

                    //NewVersion = "";
                    Versions.Clear();
                    Documents.Clear();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Une erreur s'est produite :\n" + e.Message, "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            
        }


      
        public ICommand AddModuleCommand
        {
            get
            {
                if (this.addModuleCommand == null)
                    this.addModuleCommand = new RelayCommand(param => this.AjouterModule(param));

                return this.addModuleCommand;
            }
        }

        /// <summary>
        /// Ajout d'un module à l'ECF
        /// </summary>
        /// <param name="param">Module</param>
        public void AjouterModule(object param)
        {
            if (param != null)
            {
                ModuleES m = param as ModuleES;
                ModulesUtilises.Add(m);
                ModulesRestants.Remove(m);
            }
        }


        public ICommand DelModuleCommand
        {
            get
            {
                if (this.delModuleCommand == null)
                    this.delModuleCommand = new RelayCommand(param => this.EnleverModule(param));

                return this.delModuleCommand;
            }
        }

        /// <summary>
        /// Enlève un module à l'ECF
        /// </summary>
        /// <param name="param">Module</param>
        public void EnleverModule(object param)
        {
            if (param != null)
            {
                ModuleES m = param as ModuleES;
                ModulesRestants.Add(m);
                ModulesUtilises.Remove(m);
            }
        }


        public ICommand AddCompetenceCommand
        {
            get
            {
                if (this.addCompetenceCommand == null)
                    this.addCompetenceCommand = new RelayCommand(param => this.AjouterCompetence(param));

                return this.addCompetenceCommand;
            }
        }

        /// <summary>
        /// Ajoute une compétence à l'ECF
        /// </summary>
        /// <param name="param">Compétence</param>
        public void AjouterCompetence(object param)
        {
            if (param != null)
            {
                CompetenceES c = param as CompetenceES;
                CompetencesUtilisees.Add(c);
                CompetencesRestantes.Remove(c);
            }
        }


        public ICommand DelCompetenceCommand
        {
            get
            {
                if (this.delCompetenceCommand == null)
                    this.delCompetenceCommand = new RelayCommand(param => this.EnleverCompetence(param));

                return this.delCompetenceCommand;
            }
        }

        /// <summary>
        /// Elève une compétence à l'ECF
        /// </summary>
        /// <param name="param">Compétence</param>
        public void EnleverCompetence(object param)
        {
            if (param != null)
            {
                CompetenceES c = param as CompetenceES;
                CompetencesRestantes.Add(c);
                CompetencesUtilisees.Remove(c);
            }
        }


        public ICommand DeleteECFCommand
        {
            get
            {
                if (this.deleteECFCommand == null)
                    this.deleteECFCommand = new RelayCommand(param => this.SupprimerECF());

                return this.deleteECFCommand;
            }
        }

        /// <summary>
        /// Supprime définitevement l'ECF courrant
        /// </summary>
        public void SupprimerECF()
        {
            if (CurrentECF != null)
            {
                if (MessageBox.Show("Voulez vous supprimer cet ECF ?", "Supprimer", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try 
                    {
                        FacadeServices.GetInstance().SupprimerECF(new SupprimerECFIn(CurrentECF));
                        Parent.vmMainWindow.vmBarreInfos.Message = "Suppression correctement effectué.";
                        Parent.RefreshAfterEditECF();
                        Parent.Onglets.Remove(this);
                    } 
                    catch (Exception e)
                    {
                        MessageBox.Show("Erreur lors de la suppression :\n" + e.Message, "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }



        private VersionECFES pEditVersion;
        public VersionECFES EditVersion {
            get { return pEditVersion; }
            set {
                if(value != null) {
                    pEditVersion = value;
                    RaisePropertyChanged("EditVersion");
                }

            }
        }

        private string newVersion;
        public string NewVersion {
            get { return newVersion; }
            set {
                newVersion = value;
                RaisePropertyChanged("NewVersion");
            }
        }


        private ICommand addNewVersionCommand;
        public ICommand AddNewVersionCommand {
            get {
                if(this.addNewVersionCommand == null)
                    this.addNewVersionCommand = new RelayCommand(param => this.AjouterNewVersion());

                return this.addNewVersionCommand;
            }
        }

        /// <summary>
        /// Créer une nouvelle activité
        /// </summary>
        private void AjouterNewVersion() {

            AddLibelle addwindow = new AddLibelle("");
            bool? result = addwindow.ShowDialog();
            if (result ?? false)
            {
                
                if (!string.IsNullOrWhiteSpace(addwindow.Libelle))
                {
                    VersionECFES a = new VersionECFES();
                    a.Libelle = addwindow.Libelle;
                    Versions.Add(a);
                }
                
            }
        }



        private ICommand updateVersionCommand;
        public ICommand UpdateVersionCommand {
            get {
                if(this.updateVersionCommand == null)
                    this.updateVersionCommand = new RelayCommand(param => this.UpdateVersion());

                return this.updateVersionCommand;
            }
        }

        private void UpdateVersion() {

            if (EditVersion != null)
            {

                AddLibelle addwindow = new AddLibelle(EditVersion.Libelle);
                bool? result = addwindow.ShowDialog();
                if (result ?? false)
                {

                    if (!string.IsNullOrWhiteSpace(addwindow.Libelle))
                    {
                        EditVersion.Libelle = addwindow.Libelle;
                        ICollectionView view = CollectionViewSource.GetDefaultView(Versions);
                        view.Refresh();
                    }

                }

            }

        }

        private ICommand delVersionCommand;
        public ICommand DelVersionCommand {
            get {
                if(this.delVersionCommand == null)
                    this.delVersionCommand = new RelayCommand(param => this.SupprimerVersion());

                return this.delVersionCommand;
            }
        }

        private void SupprimerVersion() {
            if(EditVersion != null) {
                Versions.Remove(EditVersion);
                if(Versions.Count > 0)
                    EditVersion = Versions[0];
            }
        }
    }

}
